package net.yebaihe.buildapp.yyh;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;

import com.waps.AppConnect;
import com.waps.UpdatePointsNotifier;

import net.yebaihe.sdk.Des2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;

public class FillAdInfo extends Activity {
	private CheckBox banner;
	private CheckBox jifen;
	private LinearLayout adProvider;
	private RadioButton youmi;
	private RadioButton waps;
	private View youmigroup;
	private View wapsgroup;
	private EditText youmiappid;
	private EditText youmiappsecret;
	private EditText wapsappid;
	private int appidx;
	private RadioGroup adgroup;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adinfo);
        banner=(CheckBox) this.findViewById(R.id.iduserbanner);
        jifen=(CheckBox) this.findViewById(R.id.idusejifen);
        banner.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				checkAdVisible();
			}
        });
        
        Button youmireg=(Button) this.findViewById(R.id.idregyoumi);
        youmireg.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse("http://www.youmi.net/register?u=6954");        
				Intent it = new Intent(Intent.ACTION_VIEW, uri);        
				startActivity(it);
			}
        });
        Button wapsreg=(Button) this.findViewById(R.id.idregwaps);
        wapsreg.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse("http://www.waps.cn/?f=108257351");        
				Intent it = new Intent(Intent.ACTION_VIEW, uri);        
				startActivity(it);
			}
        });
        
        jifen.setOnCheckedChangeListener(new  OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				checkAdVisible();
			}
        });
        
        adProvider=(LinearLayout)this.findViewById(R.id.idadprovider);
        youmi=(RadioButton) this.findViewById(R.id.idyoumi);
        waps=(RadioButton) this.findViewById(R.id.idwaps);
        adgroup=(RadioGroup)this.findViewById(R.id.idadgroup);
        
        youmi.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				checkAdProviderVisible();
			}
        });
        waps.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				checkAdProviderVisible();
			}
        });
        
        youmigroup=this.findViewById(R.id.idyoumigroup);
        wapsgroup=this.findViewById(R.id.idwapsgroup);
        
        
        Button next=(Button) this.findViewById(R.id.idnext);
        next.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if (validateAdParams()){
					int total=getWapsPoints();
					if (total>=25){
						new AlertDialog.Builder(FillAdInfo.this).setTitle("扣除积分提示")
						.setMessage("提交一次软件将扣除25个积分，您现在的积分是 "+total+",积分的获取的是免费的，多谢您的支持！")
						.setPositiveButton("继续", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (spendWapsPoints(25)){
									new AlertDialog.Builder(FillAdInfo.this).setTitle("提交应用程序")
									.setMessage("积分扣除成功，您的剩余积分为"+getWapsPoints()+",按确定按钮以后，将打开邮件客户端提交应用，请注意相关提示")
									.setPositiveButton("确定", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											if (doSubmit()){
												updateVersionAndChangeState();
											}
										}
									}).create().show();
								}
							}
						}).setNegativeButton("免费获取积分", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								showAppWall();
							}
						}).setIcon(R.drawable.icon).create().show();
					}
					else{
						new AlertDialog.Builder(FillAdInfo.this).setTitle("扣除积分提示")
						.setMessage("提交一次软件将扣除25个积分，您现在的积分("+total+")不足,请先免费获取更多积分，多谢您的支持")
						.setNegativeButton("免费获取积分", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								showAppWall();
							}
						}).setIcon(R.drawable.icon).create().show();
					}
				}
			}
        });
        
        youmiappid=(EditText) this.findViewById(R.id.idyoumiappid);
        youmiappsecret=(EditText) this.findViewById(R.id.idyouappsecret);
        wapsappid=(EditText) this.findViewById(R.id.idwapsid);
        
        loadAdParams();
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

    }

	private void loadAdParams() {
		MyHelper dbhelper = MyHelper.get(this);
		appidx=getIntent().getIntExtra("appidx", -1);
		HashMap<Integer,String>valuemap=dbhelper.getAppValueMap(appidx);
		banner.setChecked((""+valuemap.get(-101)).equals("Y"));
		jifen.setChecked((""+valuemap.get(-102)).equals("Y"));
		youmi.setChecked((""+valuemap.get(-106)).equals("youmi"));
		waps.setChecked((""+valuemap.get(-106)).equals("waps"));
		if (valuemap.containsKey(-105)) wapsappid.setText((""+valuemap.get(-105)));
		if (valuemap.containsKey(-103)) youmiappid.setText((""+valuemap.get(-103)));
		if (valuemap.containsKey(-104)) youmiappsecret.setText((""+valuemap.get(-104)));
		checkAdVisible();
	}

	protected void updateVersionAndChangeState() {
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		Cursor cursor = db.rawQuery("select * from app where _id="+appidx, null);
		if (cursor.moveToFirst()){
			int version=cursor.getInt(5);
			version+=1;
			cursor.close();
			db.execSQL("update app set versioncode="+version+" where _id="+appidx);
			cursor = db.rawQuery("select * from app where _id="+appidx, null);
			cursor.moveToFirst();
			version=cursor.getInt(5);
			Toast.makeText(this, "版本号已增加，目前的版本号是:"+version, Toast.LENGTH_LONG).show();
		}
		else{
			Toast.makeText(this, "找不到appidx:"+appidx+" 对应的应用!", Toast.LENGTH_LONG).show();
		}
		db.close();
		dbhelper.close();
	}

	protected boolean doSubmit() {
		Toast.makeText(this, "正在保存，请稍候...", Toast.LENGTH_LONG).show();
		MyHelper dbhelper = MyHelper.get(this);
		int appidx=getIntent().getIntExtra("appidx", -1);
		HashMap<Integer,String>valuemap=dbhelper.getAppValueMap(appidx);
		
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		Cursor cursor = db.rawQuery("select * from app where _id="+appidx, null);
		String cname="";
		int version=0;
		if (cursor.moveToFirst()){
			cname=cursor.getString(1);
			version=cursor.getInt(5);
		}
		db.close();
		
		
		String cnt="";
		String afterDes2="";
		Iterator<Integer> iter = valuemap.keySet().iterator(); 
		final String zippath=getZipFilePath();
		boolean zipok=false;
		try {
			java.util.zip.ZipOutputStream outZip = new java.util.zip.ZipOutputStream(new java.io.FileOutputStream(zippath));
			while (iter.hasNext()){
				Integer key = iter.next();
				String value=valuemap.get(key);
				String[] filevalues=value.split(";");
				for (int i=0;i<filevalues.length;i++){
					String[] finfo=filevalues[i].split(":");
					if ((finfo.length>0) && (finfo[0].charAt(0)=='/')){
						File f=new File(finfo[0]);
						if (f.exists()){
							XZip.ZipFiles(f.getParent()+java.io.File.separator, f.getName(), outZip);
						}
					}
				}
				cnt+=key+":"+value+"\n";
			}
			outZip.finish();
			outZip.close();
			Log.d("myown", "send cnt:"+cnt);
			afterDes2=Des2.encode("_2build@",cnt);
			zipok=true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		final String subject="buildapp:"+cname+" "+version;
		final String mycode=afterDes2;
		Toast.makeText(this, "将发送的邮件附件大小为"+new File(zippath).length()+"个字节",Toast.LENGTH_LONG).show();
		if (zipok){
			new Handler().postDelayed(new Runnable(){
				@Override
				public void run() {//for the zip file flush
					Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
					emailIntent.addCategory(Intent.CATEGORY_DEFAULT);
					String type = getMimeTypeByName(FillAdInfo.this, zippath);
					emailIntent.setType(type);			
				    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"androidlily@sina.com"}); 
				    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); 
				    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
				    "请不要修改下面两段横线之间的任何内容，否则可能无法正确创建您的应用\n\n--------------------------------------------------\n\n"
				    		+mycode+"\n\n--------------------------------------------------\n\n"); 
				    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+ zippath));
				    startActivityForResult(Intent.createChooser(emailIntent, "提交应用信息..."),1);			
				}
			}, 1000);
		}
		else{
			Toast.makeText(FillAdInfo.this, "打包应用失败:"+zippath, Toast.LENGTH_LONG).show();
			return false;
		}
		
		return true;
	}
	
	public static String getMimeTypeByName(Context context, String name) {
	       
        if (null == name || 0 == name.length())
            return null;

        String extension = null;
        int dot = name.lastIndexOf(".");
        if (dot >= 0) {
            extension=  name.substring(dot+1);
        }

        // get mimetype with the MimeTypeMap class in android
        String sys = null;
        if(extension != null)
            sys = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

        return sys;
    }

	private String getZipFilePath() {
		int appidx=getIntent().getIntExtra("appidx", -1);
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		Cursor cursor = db.rawQuery("select * from app where _id="+appidx, null);
		String ename="app_";
		int version=0;
		if (cursor.moveToFirst()){
			ename+=cursor.getString(2);
			version=cursor.getInt(5);
		}
		db.close();
		dbhelper.close();
		new File(Environment.getExternalStorageDirectory()+"/buildapp/zips/").mkdirs();
		return Environment.getExternalStorageDirectory()+"/buildapp/zips/"+ename+"_"+version+".zip";
	}

	protected boolean validateAdParams() {
		boolean needad=false;
		if (youmigroup.isShown()){
			needad=true;
			EditText youmiappid=(EditText) this.findViewById(R.id.idyoumiappid);
			if (youmiappid.getText().toString().length()<=0){
				Toast.makeText(this, "有米应用ID不能为空", Toast.LENGTH_LONG).show();
				return false;
			}
			EditText youmiappsecret=(EditText) this.findViewById(R.id.idyouappsecret);
			if (youmiappsecret.getText().toString().length()<=0){
				Toast.makeText(this, "有米应用密码不能为空", Toast.LENGTH_LONG).show();
				return false;
			}
		}
		if (wapsgroup.isShown()){
			needad=true;
			EditText wapsappid=(EditText) this.findViewById(R.id.idwapsid);
			if (wapsappid.getText().toString().length()<=0){
				Toast.makeText(this, "万普应用ID不能为空", Toast.LENGTH_LONG).show();
				return false;
			}
		}
		if (needad && (!youmi.isChecked()) && (!waps.isChecked())){
			Toast.makeText(this, "请选择广告平台！", Toast.LENGTH_LONG).show();
			return false;
		}
		saveAdParams();
		return true;
	}

	private void saveAdParams() {
		int appidx=getIntent().getIntExtra("appidx", -1);
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		String sql="delete from aparams where aid="+appidx+" and tid<0";
		db.execSQL(sql);
		String tmp;
		tmp="N"; if (banner.isChecked()) tmp="Y";
		sql="insert into aparams (aid,tid,value) values ("+appidx+",-101,'"+tmp+"')";
		db.execSQL(sql);
		tmp="N"; if (jifen.isChecked()) tmp="Y";
		sql="insert into aparams (aid,tid,value) values ("+appidx+",-102,'"+tmp+"')";
		db.execSQL(sql);
		if (adProvider.isShown()){
			if (youmi.isChecked()){
				sql="insert into aparams (aid,tid,value) values ("+appidx+",-103,'"+youmiappid.getText().toString()+"')";
				db.execSQL(sql);
				sql="insert into aparams (aid,tid,value) values ("+appidx+",-104,'"+youmiappsecret.getText().toString()+"')";
				db.execSQL(sql);
				sql="insert into aparams (aid,tid,value) values ("+appidx+",-106,'youmi')";
				db.execSQL(sql);
			}
			else if (waps.isChecked()){
				sql="insert into aparams (aid,tid,value) values ("+appidx+",-105,'"+wapsappid.getText().toString()+"')";
				db.execSQL(sql);
				sql="insert into aparams (aid,tid,value) values ("+appidx+",-106,'waps')";
				db.execSQL(sql);
			}
		}
		db.close();
		dbhelper.close();
	}

	protected void checkAdVisible() {
		if ((banner.isChecked()) || (jifen.isChecked())){
			adProvider.setVisibility(View.VISIBLE);
		}
		else{
			adProvider.setVisibility(View.GONE);
		}
		checkAdProviderVisible();		
		if ((!youmi.isChecked()) && (!waps.isChecked())){
			adgroup.clearCheck();
			waps.setChecked(true);
		}
	}

	private void checkAdProviderVisible() {
		if (adProvider.getVisibility()==View.VISIBLE){
			if (youmi.isChecked()){
				youmigroup.setVisibility(View.VISIBLE);
			}
			else{
				youmigroup.setVisibility(View.GONE);
			}
			if (waps.isChecked()){
				wapsgroup.setVisibility(View.VISIBLE);
			}
			else{
				wapsgroup.setVisibility(View.GONE);
			}
		}
		else{
			youmigroup.setVisibility(View.GONE);
			wapsgroup.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode==RESULT_OK){
			Toast.makeText(this, "请确认您的邮件已经成功发送，您将很快收到相应的apk安装文件！", Toast.LENGTH_LONG).show();
		}
	}
	int totalPoints=-1;
	protected int getWapsPoints() {
		//return AppOffersManager.getPoints(this);
        UpdatePointsNotifier cb=new UpdatePointsNotifier(){
            public void getUpdatePoints(String arg0, int arg1) {
                totalPoints=arg1;
                synchronized (this) {this.notify();}
            }
            public void getUpdatePointsFailed(String arg0) {
                totalPoints=-1;
                synchronized (this) {this.notify();}
            }
        };
        AppConnect.getInstance(this).getPoints(cb);
        try {
            synchronized (cb) { cb.wait();}
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return totalPoints;
    }
  
    protected boolean spendWapsPoints(int spendTotal2) {
    	//return AppOffersManager.spendPoints(this,spendTotal2);
        UpdatePointsNotifier cb=new UpdatePointsNotifier(){
            public void getUpdatePoints(String arg0, int arg1) {
                totalPoints=arg1;
                synchronized (this) {this.notify();}
            }
            public void getUpdatePointsFailed(String arg0) {
                totalPoints=-1;
                synchronized (this) {this.notify();}
            }
        };
        AppConnect.getInstance(this).spendPoints(spendTotal2, cb);
        try {
            synchronized (cb) {cb.wait();}
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return totalPoints>=0;
    }
	
    protected void showAppWall(){
		AppConnect.getInstance(this).showOffers(this);
    }
	
}
